package org.fujene.memoryblock;

import java.util.Arrays;


// The new memory block, with message-pack
abstract class MemoryAbstractBlock{
	private byte[] source;
//	private int[] headers;
//	private int blockID;
	private int blockLength;
//	private Class[] structure;

//	private MemoryAbstractBlock(){/* No constructor */}

	protected abstract void setStructure();

	public abstract MemoryAbstractBlock create();

	// Read without message-packed
	public synchronized byte[] readRawBytes(int from, int length){
		if(from + length > blockLength || length < 0 || from < 0)
			throw new IndexOutOfBoundsException("Illegal specification: from - " + from + " length - "
					+ length + " range - " + blockLength);

		return Arrays.copyOfRange(source, from, from + length);
	}
	
	// move bytes
	protected void moveBody(int from, int length, int offset){
		if(offset == 0) return;
		synchronized(source){
			if(offset > 0){
				// move forward
				for(int i = from + length - 1; i >= from; i--)
					source[i + offset] = source[i];
			}else{
				// move backward
				for(int i = from; i < from + length - 1; i++)
					source[i + offset] = source[i];
			}
		}
	}
	
	public void register(byte[] b){
		this.source = b;
	}

	public byte[] returnBlock(){
		return this.source;
	}
}
